package com.thh.create;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thh.pojo.Book;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;

/**
 * 演示ES的Document的修改
 */
public class App03_UpdateDocument {

    //定义客户端
    TransportClient client;

    /*
    文档创建三：JavaBean
     */
    @Test
    public void test3() throws Exception  {
        //创建:   {"id":1,"bookname":"xxxxx","price":56}
        Book book = new Book();
        book.setId(8);
        book.setBookname("小灰灰真的好骚啊！");
        book.setPic("88888.jpg");
        book.setPrice(29000L);
        book.setBookdesc("可描述的书，可以复制！！");


        //把对象转成json字符串
        ObjectMapper om = new ObjectMapper();
        String bookStr = om.writeValueAsString(book);

        //创建文档
        client.prepareUpdate("xiaofeifei_index","book",book.getId()+"")
                .setDoc(bookStr,XContentType.JSON) //更新后的内容放入
                .get();//执行创建

    }



    //初始化
    @Before
    public void init() throws Exception {
        //1、创建一个Settings对象，相当于一个配置信息。主要配置集群的名称。 cluster.name配置集群名称
        Settings settings = Settings.builder().put("cluster.name","elasticsearch").build();
        //2、创建一个客户端client对象。
        client = new PreBuiltTransportClient(settings);
        //3、使用client对象创建一个索引库。
        client.addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"),9300));
    }

    //释放资源
    @After
    public void close(){
        //4、关闭client对象。
        client.close();
    }
}
